from re import T
from maix import touchscreen, display , camera , image ,app , key
from maix._maix.image import COLOR_BLUE, COLOR_GRAY, COLOR_RED

class TouchThreshold:
    def __init__(self):
        self.x = 0
        self.last_x = 0
        self.y = 0
        self.last_y = 0
        self.press = 0
        self.last_press = False
        self.pressed_already  = False
        self.tc = touchscreen.TouchScreen()
        self.threshold = []
        self.scope = 31
    
    def get_touch_data(self):
        x,y,press = self.tc.read()
        if x != self.last_x and y != self.last_y :
            self.last_x = x 
            self.last_y = y
            self.last_press = press
        
        return x,y,press        

    def add_scope(self,change:int = 5):
        self.scope += change
        print("+")

    def red_scope(self,change:int = 5):
        self.scope -= change
        print("-")

    def get_point_threshold(self,scope):
        x , y , press = self.tc.read()
        self.x ,self.y = image.resize_map_pos_reverse(img.width(),img.height(),disp.width(),disp.height(), image.Fit.FIT_CONTAIN,x,y)
        img.draw_keypoints([self.x,self.y],COLOR_BLUE)
        if int(scope/2) == (scope/2):  # 偶数
            stat = img.get_statistics(roi=[self.x - scope/2,self.y - scope/2,scope+1,scope+1])
        else :                     # 奇数
            stat = img.get_statistics(roi=[self.x - int(scope/2),self.y - int(scope/2),scope,scope])
        return stat

    def get_area_threshold(self):
        img.draw_rect(int(img.width()/2) - int(self.scope/2),int(img.height()/2) - int(self.scope/2),self.scope+1,self.scope+1,COLOR_RED)
        if int(self.scope/2) == (self.scope/2):  # 偶数
            stat = img.get_statistics(roi=[int(img.width()/2) - int(self.scope/2),int(img.height()/2) - int(self.scope/2),self.scope+1,self.scope+1])
        else :                                   # 奇数
            stat = img.get_statistics(roi=[int(img.width()/2) - int(self.scope/2),int(img.height()/2) - int(self.scope/2),self.scope,self.scope])
       # 计算L通道阈值 (范围: 0~100)
        L_IQR = stat.l_uq() - stat.l_lq()
        L_min = max(0,   stat.l_lq() - 1.5 * L_IQR)  # 不低于0
        L_max = min(100, stat.l_uq() + 1.5 * L_IQR)  # 不高于100

        # 计算A通道阈值 (范围: -128~127)
        A_IQR = stat.a_uq() - stat.a_lq()
        A_min = max(-128, stat.a_lq() - 1.5 * A_IQR)  # 不低于-128
        A_max = min(127,  stat.a_uq() + 1.5 * A_IQR)  # 不高于127

        # 计算B通道阈值 (范围: -128~127)
        B_IQR = stat.b_uq() - stat.b_lq()
        B_min = max(-128, stat.b_lq() - 1.5 * B_IQR)
        B_max = min(127,  stat.b_uq() + 1.5 * B_IQR)
        self.threshold = [[int(L_min),int(L_max),int(A_min),int(A_max),int(B_min),int(B_max)]]
        print(self.threshold)
    
    def threshold_rect(self):
        img.draw_keypoints([int(img.width()/2),int(img.height()/2)],color=COLOR_RED)
        if int(self.scope/2) == (self.scope/2):  # 偶数
            img.draw_rect(int(img.width()/2)- int(self.scope/2),int(img.height()/2) - int(self.scope/2),self.scope+1,self.scope+1,color=COLOR_BLUE)
        else :
            img.draw_rect(int(img.width()/2)- int(self.scope/2),int(img.height()/2) - int(self.scope/2),self.scope,self.scope,color=COLOR_BLUE)

    def touch_check(self,start_x,start_y,want_string:str,func,x,y,press):
        str_size = image.string_size(want_string)
        str_position = [start_x, start_y, 10*7 + str_size.width(), 10 *4 + str_size.height()]
        img.draw_string(start_x+6, start_y+6, want_string, image.COLOR_WHITE,scale=2)
        img.draw_rect(str_position[0], str_position[1], str_position[2], str_position[3],  image.COLOR_WHITE, 2)
        exit_btn_disp_pos = image.resize_map_pos(img.width(), img.height(), disp.width(), disp.height(), image.Fit.FIT_CONTAIN, str_position[0], str_position[1], str_position[2], str_position[3])
        if press:
            self.pressed_already = True
        else :
            if self.pressed_already:
                
                if is_in_button(x,y,exit_btn_disp_pos):
                    self.pressed_already = False
                    func()

def is_in_button(x, y, btn_pos):
    return x > btn_pos[0] and x < btn_pos[0] + btn_pos[2] and y > btn_pos[1] and y < btn_pos[1] + btn_pos[3]

def change_img_flag():
    global img_flag,tg
    if img_flag == 0:
        if tg.threshold:
            img_flag = 1
    elif img_flag == 1:
        img_flag = 0

cam = camera.Camera()
disp = display.Display()
tc = touchscreen.TouchScreen()
tg = TouchThreshold()



img_flag = 0
'''画面处理部分'''
'''
cam.luma(20)  # 调暗摄像头的亮度
cam.constrast()		# 设置对比度，范围[0, 100]
cam.saturation(30)		# 设置饱和度，范围[0, 100]
cam.exp_mode(0)
#cam.exposure(100)
'''

while not app.need_exit():
    img = cam.read()
    tg.threshold_rect()
    show_str = f"threshold is :{tg.threshold}"
    x,y,press = tg.get_touch_data()
    tg.touch_check(0,0,"<SURE>",tg.get_area_threshold,x,y,press)
    tg.touch_check(0,80,"<add>",tg.add_scope,x,y,press)
    tg.touch_check(0,160,"<red>",tg.red_scope,x,y,press)
    tg.touch_check(0,240,"<bay>",change_img_flag,x,y,press)
    img.draw_string(0,320,show_str,scale= 2)
    if img_flag == 0 :
        disp.show(img)
    elif img_flag == 1:
        binary_img = img.binary(tg.threshold)
        disp.show(binary_img)

    

